import formula from './formula.json';
import rgbHex from 'rgb-hex';
import color from 'css-color-function';
import axios from 'axios';

/**
 * 吧生成的样式表写入到style中
 */
export const writeNewStyle = newStyle => {
    console.log(newStyle);
    document.getElementById('theme').innerText = newStyle;
};

/**
 * 根据主题色生成样式表
 */
export const generateNewStyle = async primaryColor => {
    // 根据主题色生成色值表 param
    const colors = generateColors(primaryColor);
    // 获取当前版本element-plus的默认样式表，并且把需要替换的色值打上标记
    let data = await getOriginalStyle();
    // 遍历生成的色制表，在默认样式表进行全局替换
    Object.keys(colors).forEach(key=>{
        data = data.replace(new RegExp(
            '(:|\\s+)' + key, 'g'),
            '$1' + colors[key]
        );
    });
    return data.replace('@charset "UTF-8";','');
};

export const generateColors = (primary) => {
    if (!primary) return;
    const colors = {
        primary
    };
    Object.keys(formula).forEach(e => {
        const value = formula[e].replace(/primary/g, primary);
        colors[e] = '#' + rgbHex(color.convert(value));
    });
    return colors;
};

const getOriginalStyle = async () => {
    const version = require('element-plus/package.json').version;
    const url = `https://unpkg.com/element-plus@${version}/dist/index.css`;
    const {data} = await axios(url);
    // 把获取到的数筛选为样式模板
    return  getStyleTemplate(data);
};

/**
 * 返回style的模板
 */
const getStyleTemplate = data => {
    // element-plus 默认色值
    const colorMap = {
        '#3a8ee6': 'shade-1',
        '#409eff': 'primary',
        '#53a8ff': 'light-1',
        '#66b1ff': 'light-2',
        '#79bbff': 'light-3',
        '#8cc5ff': 'light-4',
        '#a0cfff': 'light-5',
        '#b3d8ff': 'light-6',
        '#c6e2ff': 'light-7',
        '#d9ecff': 'light-8',
        '#ecf5ff': 'light-9'
    };
    Object.keys(colorMap).forEach(e=>{
        data = data.replace(new RegExp(e,'ig'),colorMap[e]);
    });
    return data;
};